package com.ruoyi.binance.api;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.StringUtils;

import java.util.HashMap;

public class KlinesApi {

    public static JSONArray minK(String code, Long startTime, Long endTime) {
        return minK(code, startTime, endTime, "1m");
    }

    public static JSONArray min15K(String code, Long startTime, Long endTime) {
        return minK(code, startTime, endTime, "15m");
    }

    public static JSONArray minK(String code, Long startTime, Long endTime, String interval) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("symbol", code);
        paramMap.put("interval", interval);
        if(startTime == null && endTime == null){
            paramMap.put("limit", 1);
        }else {
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("limit", 1000);
        }

        String body = HttpRequest.get(Config.BASE_URL + Config.KLINES_URL)
                .form(paramMap)
                .timeout(20000)//超时，毫秒
                .execute().body();

        if (StringUtils.isBlank(body)) {
            throw new RuntimeException("请求网络异常！");
        }
        JSONArray objects = JSONArray.parseArray(body);
        return objects == null ? new JSONArray() : objects;
    }


    public static JSONObject tradingDay(String code) {
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("symbol", code);
        paramMap.put("type","FULL");

        String body = HttpRequest.get(Config.BASE_URL + Config.TRADING_DAY_URL)
                .form(paramMap)
                .timeout(20000)//超时，毫秒
                .execute().body();

        if (StringUtils.isBlank(body)) {
            throw new RuntimeException("请求网络异常！");
        }
        return JSONObject.parseObject(body);
    }

    public static void main(String[] args) {
        Config.BASE_URL = "https://testnet.binance.vision";
//        long l = System.currentTimeMillis();
//        System.out.println(l);
//        JSONArray minK = minK("XRPUSDT", l - 1000 * 60 * 60 * 24, l - 1000 * 60 * 60 * 12);
//        System.out.println(minK);
//        minK = minK("XRPUSDT", l - 1000 * 60 * 60 * 12, l);
//        System.out.println(minK);

//        JSONObject jsonObject = tradingDay("XRPUSDT");
//        System.out.println(jsonObject);
//        System.out.println("开始时间：" + jsonObject.getDate("openTime"));
//        System.out.println("结束时间：" + jsonObject.getDate("closeTime"));

//        long l = System.currentTimeMillis();
//        System.out.println(l);
//        JSONArray minK = minK("XRPUSDT", l - 1000 * 60 * 60 * 24 * 4, l, "1d");
//        System.out.println(minK);

        JSONArray minK = minK("XRPUSDT", null, null);
        System.out.println(minK);
    }
}
